﻿@using Kooboo.CMS.Content.Models
@using Newtonsoft.Json
@{
    var folderManager = Kooboo.CMS.Content.Services.ServiceFactory.TextFolderManager;
    var folderTrees = folderManager.FolderTrees(Repository.Current);
}
<script type="text/javascript">
    $(function(){

        var metadata= {
            controlTypes : @Html.Raw(JsonConvert.SerializeObject(ControlHelper.ResolveAll(), Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects })),
            validationTypes : @Html.Raw(JsonConvert.SerializeObject(Enum.GetNames(typeof(ValidationType)), Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects })),
            rawEmptyColumn : @Html.Raw(JsonConvert.SerializeObject(new Column(), Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects })) ,
            rawEmptySelectListItem : @Html.Raw(JsonConvert.SerializeObject(new Kooboo.CMS.Form.SelectListItem(), Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects })) ,
            rawEmptyStringDictionary : @Html.Raw(JsonConvert.SerializeObject(new Dictionary<string, string>(), Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects })) ,
            folderTrees : @Html.Raw(JsonConvert.SerializeObject(folderTrees, Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.None }))  ,
            validationRules : {
                '@ValidationType.Required' : @Html.Raw(JsonConvert.SerializeObject(new RequiredValidation(), Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects })),
                '@ValidationType.Unique' : @Html.Raw(JsonConvert.SerializeObject(new UniqueValidation(), Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects })),
                '@ValidationType.StringLength' : @Html.Raw(JsonConvert.SerializeObject(new StringLengthValidation(), Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects })),
                '@ValidationType.Range' : @Html.Raw(JsonConvert.SerializeObject(new RangeValidation(), Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects })),
                '@ValidationType.Regex': @Html.Raw(JsonConvert.SerializeObject(new RegexValidation(), Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects }))          
                }
        };
        var DicObject = function(key, value) {
            this.Key = ko.observable(key);
            this.Value = ko.observable(value);
        };
        var SchemaViewModel = function(){
            var self = this;
            var rawViewModelData = @Html.Raw(JsonConvert.SerializeObject(Model, Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects }))  ;
            var viewModelMappingOptions = {
                'Columns': {
                    key: function(column) {
                        return ko.utils.unwrapObservable(column.Name);
                    }
                }
                ,'Validations': {
                    create:function(parameter) {
                        var validation = parameter.data;
                        if (validation != null) {
                            var typeString = validation['$type'].split(',')[0].split('.')[3].toString();
                            validation.Type = typeString.replace('Validation','');
                        }
                        return validation;
                    }
                },
            };    
            self.metadata = metadata;
            self.schemaModel=ko.mapping.fromJS(rawViewModelData,viewModelMappingOptions);
            //sort the columns
            self.schemaModel.SortColumns = function() {                
                this.Columns.sort(function(left, right) {
                    return left.Order() < right.Order() ? -1 : 1;
                });
            };
            //delete column
            self.DeleteColumn = function(column) {
                if ( confirm('@("Are you sure you want to delete this item?".Localize())') ) {
                    self.schemaModel.Columns.remove(column);            
                    window.leaveConfirm.stop();
                }
            };
            //add & edit column
            self.AddNewColumn = function() {
                var column = ko.mapping.fromJS(metadata.rawEmptyColumn);
                var columnsNumber = self.schemaModel.Columns().length;
                if (columnsNumber <= 0) {
                    column.Summarize(true);
                    column.ShowInGrid(true);
                }
                column.IsExistedColumn = ko.observable(false);
                column.Order(columnsNumber + 1);
                column.ControlType('TextBox');
                Utilities.ShowDialog(column);                 
                window.leaveConfirm.stop();
            };
            self.EditColumn = function(column) {
                var shadowColumn = Utilities.CloneObject(column);
                shadowColumn.IsExistedColumn = ko.observable(true);
                Utilities.ShowDialog(shadowColumn);
                window.leaveConfirm.stop();
            };
            
            self.Submit = function() {
                var data = ko.mapping.toJSON(self.schemaModel);
                if ($('#column-display-grid').valid()) {
                    window.loading.show();
                    $.ajax({
                        type: "POST",
                        url: location.href,
                        contentType:"application/json_net",
                        dataType:"json",
                        data: data
                    }).done(function( responseData ) {
                        parse_JsonResultData(responseData);
                    });
                }
            };
            self.schemaModel.SortColumns();   
        };
        var ColumnEditViewModel = function(column) {
            var self = this;
            self.Column = ko.observable(column);
            self.metadata = metadata;
            self.ValidationTypes = ko.observableArray();
            //custom settings
            self.AddCustomSetting = function() {
                self.Column().CustomSettingsDicObjectArray.push(new DicObject('',''));
                // self.ShowCustomSettings(true);
            };
            self.RemoveCustomSetting = function(setting) {
                self.Column().CustomSettingsDicObjectArray.remove(setting);
                if (self.Column().CustomSettingsDicObjectArray().length == 0) {
                    //self.ShowCustomSettings(false);
                }
            };
            // self.ShowCustomSettings = ko.observable(false);
            self.ShowSelectionValueContents = ko.computed(function() {
                var controlTypes = ['DropDownList', 'CheckBoxList', 'RadioList'];
                return _.indexOf(controlTypes,self.Column().ControlType()) >= 0;
            });
            self.AddSelectionItem = function() {
                var newSelectionItem = ko.mapping.fromJS(metadata.rawEmptySelectListItem);
                self.Column().SelectionItems.push(newSelectionItem);
            };
            self.RemoveSelectionItem = function(item) {
                self.Column().SelectionItems.remove(item);
            };
            self.SelectedValidationType = ko.observable('Required');
            self.AddValidationRule = function() {
                var validationObject = Utilities.CloneObject(metadata.validationRules[self.SelectedValidationType()]);
                validationObject.Type=ko.observable(self.SelectedValidationType());
                self.Column().Validations.push(validationObject);
                self.ValidationTypes.remove(self.SelectedValidationType());
                Utilities.ReSetValidation();
            };
            self.RemoveValidationRule = function(rule) {
                self.Column().Validations.remove(rule);
                if (editViewModel.ValidationTypes.indexOf(rule.Type()) < 0) {
                    self.ValidationTypes.push(rule.Type());
                }
                Utilities.ReSetValidation();
            };
            self.PersistToColumnList = function() {
                if ($('#column-edit-form').valid()) {
                    var dicArray = $('#custom-settings-container tbody tr');
                    var tempCustomSettings = {$type:ko.observable(self.Column().CustomSettings['$type'])};
                    dicArray.each(function() {
                        var dicKey = $(this).find('input[title=key]').val();
                        var dicValue = $(this).find('input[title=value]').val();
                        if ($.trim(dicKey) != '') {
                            tempCustomSettings[dicKey] = dicValue;
                        }
                    });
                    self.Column().CustomSettings = tempCustomSettings;                    
                    if (self.Column().IsExistedColumn()) {
                        var oldColumn = ko.utils.arrayFirst(shemaViewModel.schemaModel.Columns(), function(item) {
                            return item.Name() === self.Column().Name();
                        });
                        shemaViewModel.schemaModel.Columns.replace(oldColumn, Utilities.CloneObject(self.Column()));
                    } else {
                        shemaViewModel.schemaModel.Columns.push(self.Column());
                    }
                    $("#dialog").dialog("close");
                } 
            };
            self.CancelPersistToColumnList = function() {
                $("#dialog").dialog("close");
            };
        };
        var Utilities =  {
            $SortableTbody:$('#grid-field-template table tbody'),
            $FolderTree:$('#J_DataTree'),
            $EditForm:$('#column-edit-form'),
            InitSortable:function() {
                var fixHelper = function(e, ui) {
                    ui.children().each(function() {
                        $(this).width($(this).width());
                    });
                    return ui;
                };
                this.$SortableTbody.sortable({
                    helper: fixHelper,                   
                    start: function (event, ui) {
                        ui.placeholder.html('<td colspan="100"></td>');
                    },
                    stop:function(e, ui) {
                        Utilities.AdjustOrder(e, ui);      
                        ui.item.remove();
                    }
                });
            },
            CloneObject:function(obj) {
                return ko.mapping.fromJS(ko.toJS(obj));
            },
            AdjustOrder:function(e, ui) {
                var item = ko.dataFor(ui.item[0]);
                var finalPos = ui.item.index();
                // Remove from DOM
                ui.item.remove();
                // Move in KO
                shemaViewModel.schemaModel.Columns.remove(item);
                shemaViewModel.schemaModel.Columns.splice(finalPos, 0, item);
                this.$SortableTbody.children().each(function (index) {
                    //var tr =$(this).find('td.order-field');
                    //console.log(ko.dataFor(this));
                    //tr.find('input[type=hidden]').val(index + 1).change();
                    var item = ko.dataFor(this);
                    item.Order(index + 1);                    
                });
            },
            ShowDialog:function(column) {
                Utilities.InitColumn(column);
                editViewModel.Column(column);
                
                dialogTemplate.dialog({
                    title:column.Name()==null ? '' : column.Name(),
                    autoOpen:false,
                    width: 780,
                    modal: true,
                    draggable: false,
                    resizable: false,
                    open:function() {
                        Utilities.InitEditForm();
                    }
                }).dialog("open").dialog("option", "position", 'center');;   
            },
            InitEditForm:function() {                
                editViewModel.ValidationTypes.removeAll();
                $.each(metadata.validationTypes,function(i) {
                    var type = metadata.validationTypes[i];
                    var existedValidation = ko.utils.arrayFirst(editViewModel.Column().Validations(), function(rule) {
                        return rule.Type() == type;
                    });
                    if (existedValidation == null) {
                        editViewModel.ValidationTypes.push(metadata.validationTypes[i]);
                    }
                });
                dialogTemplate.find('#tabs').koobooTab().showTab(0);
                Utilities.ReSetValidation();
            },
            InitColumn:function(column) {
                column.CustomSettingsDicObjectArray = ko.observableArray();
                for (var key in column.CustomSettings) {
                    if (key != '$type') {
                        var setting = new DicObject(key,column.CustomSettings[key]); 
                        column.CustomSettingsDicObjectArray.push(setting);
                    }
                }
            },
            ReSetValidation:function(){
                Utilities.$EditForm.find('.input-validation-error').removeClass('input-validation-error').addClass('valid');
                Utilities.$EditForm.find('.field-validation-error').removeClass('field-validation-error').addClass('field-validation-valid').empty();
                Utilities.$EditForm.removeData("validator").removeData("unobtrusiveValidation");
                $.validator.unobtrusive.parse('#column-edit-form');
            },
        };       

        var dialogTemplate = $("#dialog");
        Utilities.InitSortable();        
   
        var shemaViewModel = new SchemaViewModel();
        ko.applyBindings(shemaViewModel,$('#column-display-grid')[0]);

        $('#submitContentType').click(function(e){
            e.preventDefault();
            shemaViewModel.Submit();
        });

        var editViewModel = new ColumnEditViewModel(ko.mapping.fromJS(metadata.rawEmptyColumn));
        ko.applyBindings(editViewModel,dialogTemplate[0]);
        
        dialogTemplate.find('#tabs').koobooTab();
        $.validator.addMethod('uniquecolumn', function(value) {
            var exsitedColumn = ko.utils.arrayFirst(shemaViewModel.schemaModel.Columns(), function(item) {
                return item.Name().toLowerCase() === value.toLowerCase();
            });
            return exsitedColumn == null;
        });
        $.validator.unobtrusive.adapters.addBool('uniquecolumn');
    });
</script>
